package com.pivotal.cloud.security.jwt;

import com.pivotal.cloud.crypto.codec.Codecs;
import com.pivotal.cloud.crypto.sign.SignatureVerifier;

/**
 * @className: JwtImpl
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-JwtImpl类，主要位于Security安全模块-Jwt实现者模块
 * @content: JwtImpl-Jwt实现者
 * @author: Powered by Marklin
 * @datetime: 2025-06-21 20:23
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public class JwtImpl implements Jwt {

	final JwtHeader header;

	private final byte[] content;

	private final byte[] crypto;

	private String claims;

	public JwtImpl(JwtHeader header, byte[] content, byte[] crypto) {
		this.header = header;
		this.content = content;
		this.crypto = crypto;
		this.claims = Codecs.utf8Decode(content);
	}

	@Override
	public void verifySignature(SignatureVerifier verifier) {
		verifier.verify(this.signingInput(), this.crypto);
	}

	private byte[] signingInput() {
		return Codecs.concat(new byte[][] { Codecs.b64UrlEncode(this.header.bytes()), JwtHelper.PERIOD,
				Codecs.b64UrlEncode(this.content) });
	}

	@Override
	public byte[] bytes() {
		return Codecs.concat(new byte[][] { Codecs.b64UrlEncode(this.header.bytes()), JwtHelper.PERIOD,
				Codecs.b64UrlEncode(this.content), JwtHelper.PERIOD, Codecs.b64UrlEncode(this.crypto) });
	}

	@Override
	public String getClaims() {
		return Codecs.utf8Decode(this.content);
	}

	@Override
	public String getEncoded() {
		return Codecs.utf8Decode(this.bytes());
	}

	public JwtHeader header() {
		return this.header;
	}

	@Override
	public String toString() {
		return this.header + " " + this.claims + " [" + this.crypto.length + " crypto bytes]";
	}

}
